package com.example.shiro.shiro.service.impl;

import com.example.shiro.shiro.model.SysUser;
import com.example.shiro.shiro.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author chong
 * @create 2020/3/27
 * Desc:
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public SysUser queryByName(String name) {
        String sql = "select *  from sysuser where loginName = ?";
        SysUser sysUser = jdbcTemplate.queryForObject(sql, new RowMapper<SysUser>() {
            @Override
            public SysUser mapRow(ResultSet rs, int rowNum) throws SQLException {
                SysUser user = new SysUser();
                user.setUserId(rs.getLong("userId"));
                user.setLoginName(rs.getString("loginName"));
                user.setPassword(rs.getString("password"));
                user.setType(rs.getInt("type"));
                return user;
            }
        }, name);
        return sysUser;
    }

    @Override
    public void add(SysUser sysUser) {
        String sql = "insert into SysUser (name,loginName,phone,password) values (?,?,?,?)";
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement ps = con.prepareStatement(sql.toString(), PreparedStatement.RETURN_GENERATED_KEYS);
                ps.setString(1,sysUser.getName());
                ps.setString(2,sysUser.getLoginName());
                ps.setString(3,sysUser.getPhone());
                ps.setString(4,sysUser.getPassword());
                return ps;
            }
        });
    }
}
